package com.session.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DemoSessionServlet extends HttpServlet {

	private static final long serialVersionUID = -2848044814207403494L;

	@SuppressWarnings("rawtypes")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		response.setContentType("test/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>demo session</title></head>");
		out.println("<body>");
		if (session.isNew()) {
			out.println("<h2>新建的Session对象</h2><br>");
		} else {
			out.println("<h2>不是新建的Session对象</h2><br>");
		}
		session.setMaxInactiveInterval(3600);
		out.println("<2>超时时间：" + session.getMaxInactiveInterval() + "</h2>");
		out.println("<2>ID：" + session.getId() + "</h2>");
		out.println("<2>last Access time："
				+ (new Date(session.getLastAccessedTime())) + "</h2>");
		out.println("<2>创建时间：" + (new Date(session.getCreationTime()))
				+ "</h2>");
		Integer counter = (Integer) session.getAttribute("count");
		if (counter == null) {
			counter = 1;
		} else {
			counter++;
		}
		session.setAttribute("count", counter);

		Enumeration enumer = session.getAttributeNames();
		String name = null;
		while (enumer.hasMoreElements()) {
			name = (String) enumer.nextElement();
			out.println("<2>hey：" + name + "</h2>");
			out.println("<2>value：" + session.getAttribute(name) + "</h2>");

		}

		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
